package com.hliushi.lock.web;

import com.hliushi.lock.entity.Dlock;
import com.hliushi.lock.service.DlockService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author llhuang10
 * @date 2021/10/26 11:41
 */
@Slf4j
@RestController
@RequestMapping("/db")
public class DBLockController {

    @Resource
    private DlockService dlockService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     *
     */
    @GetMapping("/stock5")
    public String stock5() {
        Dlock dlock = new Dlock();
        dlock.setMethodName("stock5");
        try {
            // 插入数据, 如果不抛异常则表示插入成功, 即获得锁
            dlockService.save(dlock);
            // 当前线程获取锁, 可以执行下面的业务代码
            int stock = Integer.parseInt(stringRedisTemplate.opsForValue().get("stock"));
            if (stock > 0) {
                stock--;
                stringRedisTemplate.opsForValue().set("stock", stock + "");
                System.out.println("库存扣减成功，剩余库存：" + stock);
            } else {
                System.out.println("库存不足！！！");
            }

            // 释放锁
            dlockService.deleteByMethodName("stock5");
        } catch (Exception e) {
            log.error("error : {}", e.getMessage());
            System.out.println("没有获取锁，不能执行减库存操作！！！");
        }
        return "OK";
    }
}
